package comnet.daytime;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, Nov 14, 2007
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

public class DayTimeServer {
    public static final int MAXBUF = 1024;
    private DatagramSocket sock;
    private int port;
    public static int connections = 0;
    private byte[] buffer;

    private DayTimeServer(int port) {
        sock = null;
        this.port = port;
        buffer = new byte[MAXBUF];
    }

    public static void main(String[] args) {
        int p = 0;

        if (args.length > 0) {
            try {
                p = Integer.parseInt(args[0]);

                if (p < 0 || p > 65535) {
                    System.out.println("Error in port number. Valid values: 0 - 65535");
                    return;
                }
            } catch (NumberFormatException nfe) {
                p = 13;
            }
        }

        new DayTimeServer(p).runServer();
    }

    /**
     * Starts the server to listen at the specified port. When a packet is
     * received the server replies with the current time at the server.
     */
    public void runServer() {
        System.out.println("Starting server on port " + port);
        try {
            sock = new DatagramSocket(port);
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            System.out.println("Server started\n");
            while (true) {
                connections++;
                sock.receive(packet);

                String message = new Date().toString();
                sock.send(new DatagramPacket(message.getBytes(), message.getBytes().length, packet.getSocketAddress()));

                InetAddress client = packet.getAddress();
                System.out.println(connections + ": " + client.getHostAddress() + " (" + client.getCanonicalHostName() + ")");
            }
        }
        catch (IOException ie) {
            System.out.println(ie.toString());
        } finally {
            if (sock != null) {
                sock.close();
            }
        }
    }
}
